<template>
  <div>
    <el-row>
      <p class='p_hr'>商品图片</p>
      <el-col :span='12'>
        <el-form ref="form" :rules="rules" label-width="120px" label-position='top'>
          <el-form-item
            label="商城首页推荐位图 （图片要求：长：高=4:3，像素要求大于750*550，仅允许上传1张图）"
            prop ='recommendImage'
          >
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              name='images'
              :show-file-list="false"
              :on-success="handleAvatarScucess('index')"
              :file-list="picRecommend"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrlForIndex" :src="imageUrlForIndex" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item
            label="商城列表页展位图 （图片要求：长：高=1:1，像素要求大于550*550，仅允许上传1张图）"
            prop ='listImage'
          >
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              name='images'
              :show-file-list="false"
              :on-success="handleAvatarScucess('list')"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrlForList" :src="imageUrlForList" class="avatar avatar-list-img">
              <i v-else class="el-icon-plus avatar-uploader-icon avatar-list-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item
            label="轮播图（默认首位的图片是主图，如需改变主图，请将图片移动至首位，轮播图限制最多5张图）"
            prop ='switchImageList'
          >
            <p><el-button type="primary" @click='cheanSwitch'>清空轮播图片</el-button></p>
            <el-upload
              ref = 'switchImageList'
              class="upload-demo"
              :before-upload="beforeAvatarUploadSwipe"
              :action="uploadUrl"
              name='images'
              drag
              multiple
              :on-preview="handlePreview"
              :on-remove="handleSwitchRemove"
              :on-success="handleSwitchSuccess"
              :file-list="picListSwipe"
              list-type="picture"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">文件大小在3M以内,像素大于550*550</div>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>

          <el-form-item
            label="详情图（暂时按照通过图片方式实现，文件大小在3M以内，仅支持JPG、GIF、PNG格式；）"
            prop ='detailImageList'
          >
          <p><el-button type="primary"  @click='cheanDetail'>清空详情图片</el-button></p>
            <el-upload
              ref = 'detailImageList'
              class="upload-demo"
              :action="uploadUrl"
              name='images'
              drag
              multiple
              :on-success="handleDetailSuccess"
              :on-preview="handlePreview"
              :on-remove="handleDetailRemove"
              :file-list="picListDetail"
              list-type="picture"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">文件大小在3M以内,像素大于550*550</div>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  export default {
    props: ['recommendImage', 'listImage', 'switchImageList', 'detailImageList'],
    data () {
      let that = this
      return {
        uploadUrl: '/mall-admin-web/file/uploadImages.do',
        imageUrlForIndex: '',
        imageUrlForList: '',
        picRecommend: [],
        pciList: [],
        picListSwipe: [],
        picListDetail: [],
        form: {
          recommendImage: '',
          listImage: '',
          switchImageList: [],
          detailImageList: []
        },
        rules: {
          recommendImage: [
            {
              required: true,
              message: '请上传商城首页推荐位图',
              validator: function (rule, value, callback) {
                if (!that.form.recommendImage) {
                  callback(new Error('请上传商城首页推荐位图'))
                }
                callback()
              }
            }
          ],
          listImage: [
            {
              required: true,
              message: '请上传商城列表页展位图',
              validator: function (rule, value, callback) {
                if (!that.form.listImage) {
                  callback(new Error('请上传商城列表页展位图'))
                }
                callback()
              }
            }
          ],
          switchImageList: [
            {
              type: 'array',
              required: true,
              message: '请上传轮播图',
              validator: function (rule, value, callback) {
                if (!that.form.switchImageList || that.form.switchImageList.length === 0) {
                  callback(new Error('请上传轮播图'))
                }
                callback()
              }
            }
          ],
          detailImageList: [
            {
              type: 'array',
              required: true,
              message: '请上传详情图',
              validator: function (rule, value, callback) {
                if (!that.form.detailImageList || that.form.detailImageList.length === 0) {
                  callback(new Error('请上传详情图'))
                }
                callback()
              }
            }
          ]
        }
      }
    },
    watch: {
      'recommendImage': function () {
        this.imageUrlForIndex = this.recommendImage
        this.form.recommendImage = this.recommendImage
        this.picRecommend.push({
          name: '',
          url: this.recommendImage
        })
      },
      'listImage': function () {
        this.imageUrlForList = this.listImage
        this.form.listImage = this.listImage
      },
      'switchImageList': function () {
        this.switchImageList.forEach((item) => {
          this.picListSwipe.push({
            name: '',
            url: item
          })
        })
        this.form.switchImageList = this.switchImageList
      },
      'detailImageList': function () {
        this.form.detailImageList = this.detailImageList
        this.detailImageList.forEach((item) => {
          this.picListDetail.push({
            name: '',
            url: item
          })
        })
      },
      'form.recommendImage': function () {
        this.$refs.form.validateField('recommendImage')
      },
      'form.listImage': function () {
        this.$refs.form.validateField('listImage')
      },
      'form.switchImageList': function () {
        this.$refs.form.validateField('switchImageList')
      },
      'form.detailImageList': function () {
        this.$refs.form.validateField('detailImageList')
      }
    },
    methods: {
      getFormData () {
        return this.form
      },
      formValidation () {
        let result
        this.$refs.form.validate(function (boolean) {
          result = boolean
        })
        return result
      },
      handleAvatarScucess (type) {
        let that = this
        return function (res, file) {
          if (type === 'index') {
            that.imageUrlForIndex = file.url
            that.form.recommendImage = res.data[0]
          } else if (type === 'list') {
            that.imageUrlForList = file.url
            that.form.listImage = res.data[0]
          }
        }
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isLt2M
      },
      beforeAvatarUploadSwipe () {
        if (this.form.switchImageList.length >= 5) {
          this.$message.error('轮播图限制最多5张图')
          return false
        }
        return true
      },
      handlePreview (file) {
      },
      handleSwitchSuccess (response, file, fileList) {
        let picList = this.setFileListToUploadList(fileList)
        this.form.switchImageList = picList
      },
      handleSwitchRemove (file, fileList) {
        let picList = this.setFileListToUploadList(fileList)
        this.form.switchImageList = picList
      },
      handleDetailSuccess (response, file, fileList) {
        let picList = this.setFileListToUploadList(fileList)
        this.form.detailImageList = picList
      },
      handleDetailRemove (file, fileList) {
        let picList = this.setFileListToUploadList(fileList)
        this.form.detailImageList = picList
      },
      cheanSwitch () {
        this.$refs.switchImageList.clearFiles()
        this.form.switchImageList = []
        this.form.picListSwipe = []
      },
      cheanDetail () {
        this.$refs.detailImageList.clearFiles()
        this.form.detailImageList = []
        this.form.picListDetail = []
      },
      setFileListToUploadList (fileList) {
        let picList = []
        fileList.forEach(function (element, index) {
          if (element.response) {
            picList.push(element.response.data[0])
          }
          // else {
          //   picList.push(element.url)
          // }
        })
        return picList
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 200px;
    height: 150px;
    display: block;
  }
  .avatar-list-icon{
    width: 200px;
    height: 200px;
    line-height: 200px;
  }
  .avatar-list-img{
    width: 200px;
    height: 200px;
  }
  .el-upload-list__item.is-ready{
    display: none;
  }
</style>
